#!/usr/bin/env python3

# 兴盛优选

# import http.client as http_client
# http_client.HTTPConnection.debuglevel = 1
from datetime import datetime
import csv
from json import loads
from pprint import pprint
from lnglat import lnglat
from cache import Cache

COL=['areaName','areaId','storeId','storeCode','storeSign','storeName','logoUrl','storeDescription','detailAddress','mapX','mapY','contacts','storeStatus','storeStatusName','contactsTel','wechatGroupName','shopArea','userId','storeWxno','miniCodeUrl','mapAddress','range','yesterdayOrderQty','userQty','totalQty','sort']

cache = Cache('xsyx')
EXIST = set()

def fetch(city, writer):
    lnglat_li = lnglat(city)
    length = len(lnglat_li)
    total = 0

    for pos, p in enumerate(lnglat_li):
        cost = pos/length
        if pos%1000 == 0:
            print(
                str(datetime.now())[:19],
                city, length - pos,
                "%.2f%%"%(100*cost),
                int(total/cost) if cost else 0
            )
        url = f"https://mall-store.xsyxsc.com/mall-store/store/getNearStoreList?mapX={p[0]}&mapY={p[1]}&userKey=8be3d5dd-23e1-4b04-bf12-efca98d69d12"
        r = cache.get(url)['data']
        rlen = len(r)
        same = 0
        for i in r:
            if 'storePhoto' in i:
                del i['storePhoto']

            storeId = int(i['storeId'])
            yesterdayOrderQty = i['yesterdayOrderQty']
            print(yesterdayOrderQty,'yesterdayOrderQty')
            if storeId in EXIST:
                same += 1
                print(
                    "exist %.2f%%"%(same/rlen)
                )
                continue
            total+=1
            EXIST.add(storeId)

            li = [
                str(i.get(key,'') or '').replace("\r\n",' ').replace('\r',' ').replace('\n',' ') for key in COL
            ]
            writer.writerow([city]+li)


def main():
    # li = lnglat('湖南')
    # print(len(li))
    # return
    from city import CITY
    CITY += "湖南 河南 广东 江西 福建 湖北 四川 河北 陕西 广西 山东 重庆 贵州".split(' ')
    with open('xsyx.csv', 'w', encoding='utf-8-sig') as f:
        writer = csv.writer(f)
        writer.writerow(['city']+COL)
        for pos, city in enumerate(CITY,1):
            print(f"完成 {pos} 个 · {pos/len(CITY):.2%}")
            fetch(city, writer)

if __name__ == "__main__":
    import single_process.init
    main()

